package cn.aezo.minions.web.controller;

import cn.aezo.minions.common.Keys;
import cn.aezo.minions.common.Result;
import cn.aezo.minions.gen.model.User;
import cn.aezo.utils.base.ValidU;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by smalle on 2017/9/24.
 */
public class CommonController {

    public static String getUserId(HttpServletRequest request) {
        User user = getSessionUser(request);
        if(user == null) return null;

        Long id = user.getUserId();
        if(ValidU.isEmpty(id)) return null;

        return String.valueOf(id);
    }

    public static User getSessionUser(HttpServletRequest request) {
        return (User) request.getSession().getAttribute(Keys.SESSION_USER_INFO);
    }

    public static void writeJson(HttpServletResponse response, Object object) {
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json");

        PrintWriter writer = null;
        try {
            writer = response.getWriter();
        } catch (IOException e) {
            e.printStackTrace();
        }

        if(writer != null) {
            String str = "";
            if(object instanceof String) {
                str = (String) object;
            } else {
                ObjectMapper mapper = new ObjectMapper();
                try {
                    str = mapper.writeValueAsString(object);
                } catch (JsonProcessingException e) {
                    e.printStackTrace();
                }
            }

            writer.write(str);
            writer.flush();
            writer.close();
        }
    }

    public static void writeSuccess(HttpServletResponse response, String message) {
        Result result = Result.success(message);
        writeJson(response, result);
    }

    public static void writeError(HttpServletResponse response, String message) {
        Result result = Result.failure(message);
        writeJson(response, result);
    }

    public static void writeError(HttpServletResponse response, String message, Integer status) {
        Result result = Result.failure(message, status);
        writeJson(response, result);
    }

    public static Result returnSuccess(String message) {
        return Result.success(message);
    }

    public static Result returnError(String message) {
        return Result.failure(message);
    }

    public static Result returnError(String message, Integer status) {
        return Result.failure(message, status);
    }

    public static String downloadFile(HttpServletRequest request,
                               HttpServletResponse response) {
        // 如果文件名不为空，则进行下载
        String downloadRootDir = (String) request.getAttribute("downloadRootDir");
        String fileName = (String) request.getAttribute("downloadFileName");
        if(ValidU.isEmpty(fileName)) {
            fileName = request.getParameter("downloadFileName");
        }
        if (fileName != null) {
            String filePath = downloadRootDir + "/" + fileName;
            //设置文件路径
            File file = new File(filePath);

            // 如果文件名存在，则进行下载
            if (file.exists()) {
                // 实现文件下载
                byte[] buffer = new byte[1024];
                FileInputStream fis = null;
                BufferedInputStream bis = null;
                try {
                    // 配置文件下载
                    response.setHeader("content-type", "application/octet-stream");
                    response.setContentType("application/octet-stream");
                    // 下载文件能正常显示中文
                    response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));

                    fis = new FileInputStream(file);
                    bis = new BufferedInputStream(fis);
                    OutputStream os = response.getOutputStream();
                    int i = bis.read(buffer);
                    while (i != -1) {
                        os.write(buffer, 0, i);
                        i = bis.read(buffer);
                    }
                    System.out.println("Download the song successfully!");
                } catch (Exception e) {
                    System.out.println("Download the song failed!");
                } finally {
                    if (bis != null) {
                        try {
                            bis.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                    if (fis != null) {
                        try {
                            fis.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        }
        return null;
    }

    /**
     * layui 分页
     * @param list
     * @return
     */
    public static Map<String, Object> layPage(Object list) {
        Map<String, Object> map = new HashMap<>();
        if(list == null) {
            map.put("data", new ArrayList());
            map.put("count", 0);
        } else {
            if(list instanceof ArrayList) {
                map.put("data", list);
                map.put("count", ((List) list).size());
            }
        }
        map.put("code", 0);
        map.put("msg", 0);

        return map;
    }
}
